package beer.xz.beer.device.ui.test

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import beer.xz.beer.device.comm.protocol.BeerMachineStatus
import beer.xz.beer.device.comm.protocol.BeerProtocolImpl
import beer.xz.beer.device.comm.test.BeerProtocolTest
import kotlinx.coroutines.launch
import android.util.Log

/**
 * 协议测试界面
 */
@Composable
fun ProtocolTestScreen() {
    val coroutineScope = rememberCoroutineScope()
    var testResult by remember { mutableStateOf<BeerMachineStatus?>(null) }
    var testMessage by remember { mutableStateOf("") }

    // 自动运行测试
    LaunchedEffect(key1 = Unit) {
        Log.d("ProtocolTest", "开始协议测试...")
        try {
            val testData = BeerProtocolTest.generateTestPacket()
            Log.d("ProtocolTest", "生成测试数据: ${testData.size} 字节")

            // 打印测试数据的十六进制表示（前20字节和后20字节）
            val hexString = StringBuilder()
            for (i in 0 until 20) {
                hexString.append(String.format("%02X ", testData[i]))
            }
            hexString.append("... ")
            for (i in testData.size - 20 until testData.size) {
                hexString.append(String.format("%02X ", testData[i]))
            }
            Log.d("ProtocolTest", "测试数据: $hexString")

            val protocol = BeerProtocolImpl()

            // 打印数据包内容
            protocol.printPacket(testData)

            val result = protocol.decodeData(testData)

            if (result != null) {
                testResult = result
                testMessage = "解析成功"
                Log.d("ProtocolTest", "解析成功:")
                Log.d("ProtocolTest", "温度: ${result.temperature}°C")
                Log.d("ProtocolTest", "酒瓶重量: ${result.beerBottleWeight}kg")
                Log.d("ProtocolTest", "出酒量: ${result.outputBeerWeight}kg")
                Log.d("ProtocolTest", "罐装酒瓶压力: ${result.bottlePressure}kg")
                Log.d("ProtocolTest", "二氧化碳压强: ${result.co2Pressure}kg")
                Log.d("ProtocolTest", "电机行程量: ${result.motorPosition}")
                Log.d("ProtocolTest", "流量计数: ${result.flowCount}")
                Log.d("ProtocolTest", "运行时间: ${result.runningTimeMs}ms")
                Log.d("ProtocolTest", "设备ID: ${result.deviceId}")
                Log.d("ProtocolTest", "软件版本: ${result.softwareVersion}")
                Log.d("ProtocolTest", "硬件版本: ${result.hardwareVersion}")
                Log.d("ProtocolTest", "运行标志位: ${result.runningFlag}")
                Log.d("ProtocolTest", "设备状态: ${result.getStatusDescription()}")
            } else {
                testResult = null
                testMessage = "解析失败"
                Log.e("ProtocolTest", "解析失败")
            }
        } catch (e: Exception) {
            testResult = null
            testMessage = "测试异常: ${e.message}"
            Log.e("ProtocolTest", "测试异常: ${e.message}", e)
            e.printStackTrace()
        }
        Log.d("ProtocolTest", "测试完成")
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState()),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "啤酒机协议测试",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(bottom = 16.dp)
        )

        Button(
            onClick = {
                coroutineScope.launch {
                    try {
                        val testData = BeerProtocolTest.generateTestPacket()
                        val protocol = BeerProtocolImpl()
                        val result = protocol.decodeData(testData)

                        if (result != null) {
                            testResult = result
                            testMessage = "解析成功"
                        } else {
                            testResult = null
                            testMessage = "解析失败"
                        }
                    } catch (e: Exception) {
                        testResult = null
                        testMessage = "测试异常: ${e.message}"
                        e.printStackTrace()
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
        ) {
            Text("运行协议测试")
        }

        if (testMessage.isNotEmpty()) {
            Text(
                text = testMessage,
                style = MaterialTheme.typography.bodyLarge,
                modifier = Modifier.padding(vertical = 8.dp)
            )
        }

        testResult?.let { status ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp)
            ) {
                Column(
                    modifier = Modifier
                        .padding(16.dp)
                        .fillMaxWidth()
                ) {
                    Text(
                        text = "测试结果",
                        style = MaterialTheme.typography.titleLarge,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )

                    StatusItem("温度", "${status.temperature}°C")
                    StatusItem("酒瓶重量", "${status.beerBottleWeight}kg")
                    StatusItem("出酒量", "${status.outputBeerWeight}kg")
                    StatusItem("罐装酒瓶压力", "${status.bottlePressure}kg")
                    StatusItem("二氧化碳压强", "${status.co2Pressure}kg")
                    StatusItem("电机行程量", "${status.motorPosition}")
                    StatusItem("流量计数", "${status.flowCount}")
                    StatusItem("运行时间", "${status.runningTimeMs}ms")
                    StatusItem("设备ID", "${status.deviceId}")
                    StatusItem("软件版本", "${status.softwareVersion}")
                    StatusItem("硬件版本", "${status.hardwareVersion}")
                    StatusItem("运行标志位", "${status.runningFlag}")
                    StatusItem("设备状态", status.getStatusDescription())
                }
            }
        }
    }
}

@Composable
private fun StatusItem(label: String, value: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium
        )
        Text(
            text = value,
            style = MaterialTheme.typography.bodyMedium
        )
    }
}
